package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto adUserDto) {

        //参数校验

        if(adUserDto==null|| !StringUtils.isNotBlank(adUserDto.getName())||StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据用户名查询用户信息,主要是获取盐
        AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName())
                                                            .eq(AdUser::getStatus, AdminConstants.NORMAL_USER)
        );

        if(one==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        String salt = one.getSalt();

        String password = one.getPassword();
        //按照相同的加密方式加密,比对密码
        String hex = DigestUtils.md5DigestAsHex(( adUserDto.getPassword()+salt).getBytes());

        if(!password.equals(hex)){
            CustException.cust(AppHttpCodeEnum.ADMIN_OR_PASSWORD_WRONG);
        }



        //更新最后一次登录时间
        one.setCreatedTime(new Date());
        updateById(one);
        //生成token和用户信息,返回给前端

        String token = AppJwtUtil.getToken(one.getId().longValue());

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        one.setPassword(null);
        one.setSalt(null);
        map.put("user",one);

        return ResponseResult.okResult(map);
    }
}
